contextPath = contextPath || ''

layui.use(['table', 'jquery'], function () {
    var table = layui.table,
        $ = layui.jquery,
        layer = layui.layer,
        form = layui.form,
        laydate = layui.laydate;

    laydate.render({
        elem: '#pressDate',
        type: 'month'
    });

    // 搜索内容需要额外追加空内容
    $("#searchForm [name='bookTypeId']").append("<option value=''>请选择分类</option>");
    // 追加图书分类
    $.get("bookType/listAll", function (res) {
        if (res.code == 200) {
            var data = res.data;
            data.forEach(function (item) {
                $("[name='bookTypeId']").append("<option value=" + item.bookTypeId + ">" + item.name + "</option>");
            });
            form.render();
        }
    });

    var tableRen = table.render({
        elem: '#bookTable',
        url: contextPath + '/book/list',
        page: true,
        toolbar: "#toolbar",
        cols: [[
            {type: 'checkbox', fixed: 'left'},
            {field: 'name', title: '名称'},
            {
                field: 'bookNumber', 
                title: '图书编号', 
                width: 150,
                templet: function (d) {
                    if (d.bookNumber) {
                        return '<span style="font-family: monospace; font-weight: bold;">' + d.bookNumber + '</span>';
                    }
                    return '-';
                }
            },
            {
                field: 'bookTypeName', 
                title: '分类', 
                width: 300,
                templet: function (d) {
                    // 如果有分类编码，显示编码，否则只显示名称
                    if (d.bookTypeCode) {
                        return '<span class="layui-badge layui-bg-blue">' + d.bookTypeCode + '</span> ' + d.bookTypeName;
                    }
                    return d.bookTypeName || '-';
                }
            },
            {
                field: 'price', title: '价格', width: 100, templet: function (d) {
                    return '￥' + formatPrice(d.price);
                }
            },
            {field: 'author', title: '作者', width: 150},
            {
                field: 'borrowId', title: '状态', width: 100, align: 'center', templet: function (d) {
                    if (d.borrowId == null || d.borrowId == '') {
                        return '<span class="layui-badge layui-bg-green">可借</span>';
                    } else {
                        return '<span class="layui-badge layui-bg-red">已借</span>';
                    }
                }
            },
            {field: 'borrowUser', title: '借出人', width: 120},
            {field: 'borrowPhone', title: '联系方式', width: 130},
            {field: 'createDate', title: '入库时间', width: 160},
            {title: "操作", fixed: 'right', width: 220, align: "center", toolbar: "#operation"}
        ]]
    });

    table.on("tool(bookTable)", function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent == "bookUpdate") {
            $("#bookUpdateForm form")[0].reset();
            //给表单赋初值
            form.val("bookUpdateForm", data);
            layer.open({
                type: 1,
                title: "修改图书信息",
                area: ['800px', '410px'],
                content: $("#bookUpdateForm"),
                btn: ["提交", "重置", "取消"],
                success: function (layero) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'formSubmit',
                        'lay-submit': '',
                        'id': 'submitBtn'
                    });
                },
                yes: function () {
                    form.render();
                },
                btn2: function () {
                    $("#bookUpdateForm form")[0].reset();
                    return false;
                },
                btnAlign: "c"
            });
        } else if (layEvent == "bookBorrow") {
            $("#bookBorrowForm form")[0].reset();
            //给表单赋初值
            form.val("bookBorrowForm", data);
            layer.open({
                type: 1,
                title: "修改图书信息",
                area: ['500px', '300'],
                content: $("#bookBorrowForm"),
                btn: ["提交", "重置", "取消"],
                success: function (layero) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'formBorrowSubmit',
                        'lay-submit': '',
                        'id': 'submitBtn'
                    });
                },
                yes: function () {
                    form.render();
                },
                btn2: function () {
                    $("#bookBorrowForm form")[0].reset();
                    return false;
                },
                btnAlign: "c"
            });
        } else if (layEvent == "bookReturn") {
            layer.confirm("确定归还当前书籍（《" + data.name + "》）吗?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("borrow/return?borrowIds=" + [data.borrowId], null, "归还", "close");
            });
        } else if (layEvent == 'bookDelete') {
            layer.confirm("是否删除当前书籍（《" + data.name + "》）?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("book/delete?bookIds=" + [data.bookId], null, "删除", "close");
            });
        }
    });

    table.on('toolbar(bookTable)', function (obj) {
        var checks = table.checkStatus("bookTable").data;
        var ids = checks.map(check => check.bookId);
        var layEvent = obj.event;
        var len = checks.length;
        if (len == 0 && layEvent != "bookAdd" && layEvent != "search" && layEvent != "reset") {
            layer.msg("请至少选中一个图书");
            return;
        }

        if (layEvent == "bookAdd") {
            $("#bookUpdateForm form")[0].reset();
            layer.open({
                type: 1,
                title: "图书入库",
                area: ['800px', '410px'],
                content: $("#bookUpdateForm"),
                btn: ["提交", "重置", "取消"],
                success: function (layero) {
                    layero.addClass('layui-form');
                    layero.find('.layui-layer-btn0').attr({
                        'lay-filter': 'formSubmit',
                        'lay-submit': '',
                        'id': 'submitBtn'
                    });
                },
                yes: function () {
                    form.render();
                },
                btn2: function () {
                    $("#bookUpdateForm form")[0].reset();
                    return false;
                },
                btnAlign: "c"
            });
        } else if (layEvent == 'search') {
            var params = $("#searchForm form").serialize();
            tableRen.reload({
                url: contextPath + '/book/list' + jsonToUrlParams(formToJson(params))
            });
        } else if (layEvent == 'reset') {
            $("#searchForm form")[0].reset();
            tableRen.reload({
                url: contextPath + '/book/list'
            });
        } else if (layEvent == "bookReturns") {
            ids = checks.map(check => check.borrowId);
            layer.confirm("确定归还选中的" + len + "本书籍吗?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("borrow/return?borrowIds=" + ids, null, "归还", "close");
            });
        } else if (layEvent == 'bookDeletes') {
            layer.confirm("是否删除选中的" + len + "本书籍?", {
                icon: 3,
                title: '提示'
            }, function () {
                formByAjax("book/delete?bookIds=" + ids, null, "删除", "close");
            });
        }
    });

    //表单提交
    form.on("submit(formSubmit)", function (e) {
        var data = e.field;
        data.pressDate = data.pressDate + "-01";
        if (data.bookId) {
            formByAjax("book/update", data, "修改", "close");
        } else {
            formByAjax("book/add", data, "入库", "close");
        }
        return false;
    });

    form.on("submit(formBorrowSubmit)", function (e) {
        var data = e.field;
        formByAjax("borrow/borrow", data, "借出", "close");
        return false;
    });

    function formByAjax(url, data, tips, close, fun) {
        $.ajax({
            type: 'post',
            url: url,
            data: JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json',
            success: function (res) {
                if (res.code == 200) {
                    if (fun) {
                        fun.call();
                    }
                    if (close == "close") {
                        layer.closeAll();
                    }
                    table.reload("bookTable");
                    layer.msg(tips + "成功");
                } else {
                    layer.msg(tips + "失败，" + res.msg);
                }
            },
            error: function (res) {
                layer.msg(res.statusText);
            }
        });
    }
});